package com.gxa.saas.controller;


import com.gxa.saas.exception.BusinessException;
import com.gxa.saas.exception.ExceptionCode;
import com.gxa.saas.pojo.User;

import com.gxa.saas.service.UserService;
import com.gxa.saas.utils.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 员工管理
 */
@Api(value = "员工管理界面功能的说明")
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    UserService userService;

    /**
     * 当需要使用Httpsion的时候,将其声明在方法的参数中,
     * SpringMVC会自动注入该对象:
     *  HttpSession session=request,getSession();
     *  当参数中声明的时候,就从容器中找到bean并自动注入(byType)
     * @param phone
     * @param pwd
     * @param session
     */
    /**
     * produces 表示前端参数的状态
     * parm传参:用query
     * body传参:用body
     *
     * @param phone
     * @param pwd
     * @param session
     * @return
     */
    @ApiOperation(value = "登录的方法", produces = "query")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号-测试123", paramType = "query"),
            @ApiImplicitParam(name = "pwd", value = "用户密码-测试123", paramType = "query")
    })

    @PostMapping("/login")
    public Map login(String phone, String pwd, @ApiIgnore HttpSession session) throws Exception {
        //session
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        JsonResult jsonResult = new JsonResult();
        if ("123".equals(phone) && "123".equals(pwd)) {
            jsonResult.setCode("200");
            jsonResult.setMsg("登录成功");
            jsonResult.set("token", token);
            session.setAttribute("token", token);

        } else {
            throw new BusinessException(ExceptionCode.USER_LOGIN_FAILED);

        }
        return jsonResult.getMap();
    }

    @ApiOperation("添加员工的操作")
    @ApiImplicitParam(name = "user", value = "员工对象", paramType = "body", dataType = "User")
    @PostMapping("/add")
    public Map addUser(@RequestBody User user) {
        userService.addUser(user);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getMap();
    }

    @ApiOperation("重置密码的操作")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "map", value = "密码参数信息{password:string,id:int}", paramType = "body")
    })
    @PostMapping("/resetPassword")
    public Map resetPassword(@RequestBody Map map) {
        JsonResult jsonResult = new JsonResult();
        userService.resetPassword(map);

        jsonResult.setCode("200");
        return jsonResult.getMap();
    }

    @ApiOperation("修改员工信息的操作")
    @ApiImplicitParam(name = "user", value = "员工对象", paramType = "body", dataType = "User")
    @PostMapping("/update")
    public Map updateUser(@RequestBody User user) {
        userService.updateUser(user);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getMap();
    }

    @ApiOperation("根据id删除员工的操作")
    @ApiImplicitParam(name = "id", value = "员工id", dataType = "Integer")
    @PostMapping("/delete")
    public Map deleteUser(@RequestParam("id") Integer id) {
        userService.deleteUser(id);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getMap();
    }

    @ApiOperation("根据用户名或员工名字模糊查询信息的操作")
    @ApiImplicitParam(name = "map", value = "查询的参数信息", paramType = "body")
    @PostMapping("/selectByName")
    public Map selectByLikeName(@RequestBody Map map) {

        List<User> users = userService.selectByLikeName(map);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(users);
        return jsonResult.getMap();
    }

    @ApiOperation("分页查询的操作")
    @ApiImplicitParam(name = "users", value = "查询的页数", paramType = "query")
    @PostMapping("/selectByPage")
    public Map selectByPage(@RequestParam("page") Integer page) {
        List<User> users = userService.selectByPage(page);
        Integer count = userService.selectAll();
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.set("count",count);
        jsonResult.setData(users);
        return jsonResult.getMap();
    }

    @ApiOperation("改变员工启用状态的操作(data中的值{isUsed,id })")
    @PostMapping("/updateIsUsed")
    public Map updateIsUsed(@RequestBody Map map) {
        userService.updateIsUsed(map);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getMap();
    }

    @ApiOperation("获取员工总数（全查询）")
    @PostMapping("/getUserList")
    public Map getUserList() {
        List<User> userList = userService.getUserList();
        int count = userList.size();
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(userList);
        jsonResult.set("count",count);
        return jsonResult.getMap();
    }

    @ApiOperation("获取员工列表的信息")
    @PostMapping("/getUsers")
    public Map getUsers() {
        List<User> userList = userService.getUserList();
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(userList);
        return jsonResult.getMap();
    }

    @ApiOperation("上传头像的方法")
    @PostMapping(value = "/upload")
    public Map upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        //System.out.println("originalFilename:" + originalFilename);
        // 从原始文件名中获取后缀,作为新添加的文件的文件名后缀(匹配)
        String subfix = originalFilename.substring(originalFilename.indexOf(".") + 1);
        //System.out.println("subfix:" + subfix);
        //使用UUID作为文件名,保证服务器中存放的文件名唯一
        String targetFile = UUID.randomUUID().toString().replace("-", "") + "." + subfix;
        //System.out.println("targetFile:" + targetFile);
        // 通过request获取当前程序的根路径"/"
        String path = request.getSession().getServletContext().getRealPath("/");
        //System.out.println("psth:" + path);
        // 通过绝对路径
        //String path =("E:");
        String fileName = path + "upload\\image\\" + targetFile;
        //System.out.println("fileName:" + fileName);
        // 构建文件对象
        File uploadFile = new File(fileName);
        //核心操作(含有异常操作, 利用异常设定状态码(和前端约定)
        // 此处应当和ExceptionController结合, 当try执行成功则设定状态码0
        // 出现异常则设定其他
        // 再将异常信息结合BusinessException抛出, 交给ExceptionController处 理

        try {
            if (!uploadFile.exists()) {
                uploadFile.mkdirs();
            }
            multipartFile.transferTo(uploadFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("上传成功");
        jsonResult.set("pathFile", fileName);
        return jsonResult.getMap();
    }

}
